package com.wangcanxuan.www.util;

import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 配置属性读取工具类
 *
 * @author HHLJ
 * @date 2022/03/22
 */
public class PropertiesReaderUtil {
    private static volatile PropertiesReaderUtil pc = null;
    public Properties properties = null;
    /**
     * 双重锁保证单例的并发安全
     */

    private PropertiesReaderUtil(String propertiesFileName) {
        this.loadConfig(propertiesFileName);
    }

    /**
     * 获得实例
     *
     * @param propertiesFileName 属性文件的名字
     */
    public static void getInstance(String propertiesFileName) {
        if (pc == null) {
            synchronized (PropertiesReaderUtil.class) {
                if (pc == null) {
                    pc = new PropertiesReaderUtil(propertiesFileName);
                }
            }
        }

    }

    /**
     * 获得property集合
     *
     * @param name 的名字
     * @return {@link String}
     */
    public static String getProperty(String name) {
        return pc.properties.getProperty(name);
    }

    /**
     * 加载配置
     *
     * @param propertiesFileName 属性文件的名字
     */
    private void loadConfig(String propertiesFileName) {
        try (InputStream inputStream = PropertiesReaderUtil.class.getClassLoader().getResourceAsStream(propertiesFileName)) {
            properties = new Properties();
            properties.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
